package project.houseRentSystem;

/**
 * 响应 HouseView 的调用
 * 完成对房屋信息的各种操作（增删改查crud）
 */
public class HouseService {

    private House[] houses;

    private int houseNum = 1; //记录当前有多少个房屋信息

    private int idCounter = 1;//记录当前的id增长到哪个值

    //构造器
    public HouseService(int size) {
        //当创建HouseService时，指定数组大小
        houses = new House[size];
        //测试
        houses[0] = new House(1, "JACK", "112", "海淀区", 2000.0, "未出租");
    }

    public House[] list() {
        return houses;
    }

    public boolean add(House house) {
        //判断是否还可以继续添加
        if (houseNum == houses.length) {
            System.out.println("数组已满，不能添加了.....");
            return false;
        } else {
            houses[houseNum] = house;//把新对象加入到数组的最后
            houseNum++;
            //id自增长
            idCounter++;
            house.setId(idCounter);
            return true;
        }
    }

    public boolean delete(int num) {
        int index = -1;
        for (int i = 0; i < houseNum; i++) {
            if (num == houses[i].getId()) {
                index = i;//记录要删除的下标
            }
        }
        if (index == -1) {//没有找到
            return false;
        }
        //如果找到
        for (int i = index; i < houseNum - 1; i++) {
            houses[i] = houses[i + 1];
        }
        houses[houseNum - 1] = null;
        houseNum--;
        return true;
    }

    public House findById(int id) {
        //遍历
        for (int i = 0; i < houseNum; i++) {
            if (id == houses[i].getId()) {
                return houses[i];
            }
        }
        return null;
    }
}
